<template>
  <MainLayout>
    <view class="publish-page u-p-20">
      <!-- 顶部导航栏 -->
      <u-navbar 
        :leftText="'返回'" 
        :leftIcon="'arrow-left'" 
        :title="'发布信息'" 
        @leftClick="handleBack" 
        fixed 
        placeholder
      />

      <!-- 表单容器 -->
      <u-form :model="form" ref="uForm" :rules="rules" label-width="80">
        
        <!-- 类型 -->
        <u-form-item label="类型" prop="type">
          <u-radio-group v-model="form.type" placement="row">
            <u-radio v-for="(item, index) in typeList" 
                     :key="index" 
                     :name="item.value" 
                     :label="item.label" />
          </u-radio-group>
        </u-form-item>

        <!-- 出发地 -->
        <u-form-item label="出发地" prop="departure">
          <u-input v-model="form.departure" placeholder="请输入出发地" prefixIcon="map" />
        </u-form-item>

        <!-- 目的地 -->
        <u-form-item label="目的地" prop="destination">
          <u-input v-model="form.destination" placeholder="请输入目的地" prefixIcon="map" />
        </u-form-item>

        <!-- 出发时间 -->
        <u-form-item label="出发时间" prop="departureTime">
            <u-input @tap="showDate = true"
              v-model="form.departureTime" 
              placeholder="请选择出发时间"
              prefixIcon="calendar"
              readonly
            />
        </u-form-item>

        <!-- 日期选择器 -->
        <u-datetime-picker 
          v-model="dateValue" 
          :show="showDate" 
          mode="date" 
          @confirm="onDateConfirm" 
          @cancel="showDate = false" 
        />

        <!-- 座位/人数 -->
        <u-form-item :label="seatLabel" prop="seats">
          <u-input v-model.number="form.seats" type="number" :placeholder="seatPlaceholder" style="width: 100%;"  />
        </u-form-item>

        <!-- 备注 -->
        <u-form-item label="备注" prop="remark">
          <view class="textarea-wrapper">
            <u-textarea 
              v-model="form.remark" 
              placeholder="请输入备注" 
              autoHeight 
              :maxlength="maxRemark"
            />
            <text class="remark-counter" :style="{ color: remainingColor }">
              {{ form.remark.length }}/{{ maxRemark }}
            </text>
          </view>
        </u-form-item>

        <!-- 提交按钮 -->
        <u-form-item>
          <u-button type="primary" shape="circle" @click="submitForm">
            发布
          </u-button>
        </u-form-item>

      </u-form>
    </view>
  </MainLayout>
</template>

<script>
import api from '@/api'
import MainLayout from '@/layouts/MainLayout.vue'

export default {
  components: { MainLayout },
  data() {
    return {
      form: {
        type: 'personFindCar', // 默认人找车
        departure: '',
        destination: '',
        departureTime: '',
        remark: '',
        seats: null,
      },
      typeList: [
        { label: '人找车', value: 'personFindCar', seatsLabel: '人数' },
        { label: '车找人', value: 'carFindPerson', seatsLabel: '座位' }
      ],
      showDate: false,
      dateValue: Number(new Date()),
      maxRemark: 15,
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        departure: [{ required: true, message: '请输入出发地', trigger: 'blur' }],
        destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
        departureTime: [{
          validator: (rule, value, callback) => {
            if (!value) {
              callback('请选择出发时间')
              return
            }
            const selected = new Date(value)
            const now = new Date()
            if (selected.getTime() <= now.getTime()) {
              callback('出发时间必须大于当前时间')
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        seats: [{
          validator: (rule, value, callback) => {
            const label = this.seatLabel
            if (value === null || value === undefined || isNaN(value)) {
              callback(`请输入${label}`)
            } else if (value <= 0) {
              callback(`${label}必须大于0`)
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        remark: [{ max: 15, message: '备注最多15个字', trigger: 'blur' }]
      },
    }
  },
  computed: {
    seatLabel() {
      return this.form.type === 'personFindCar' ? '人数' : '座位'
    },
    seatPlaceholder() {
      return this.form.type === 'personFindCar'
        ? '请输入需要乘坐的人数'
        : '请输入可乘坐的人数'
    },
    remainingColor() {
      const remain = this.maxRemark - this.form.remark.length
      if (remain <= 0) return 'red'
      if (remain <= this.maxRemark * 0.3) return 'orange'
      return '#999'
    }
  },
  watch: {
    'form.type'() {
      if (this.$refs.uForm) {
        this.$nextTick(() => {
          this.$refs.uForm.validateField('seats')
        })
      }
    }
  },
  methods: {
    onDateConfirm(e) {
      const date = new Date(e.value)
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      this.form.departureTime = `${y}-${m}-${d}`
      this.showDate = false
    },
    async submitForm() {
      try {
        await this.$refs.uForm.validate()
        const res = await api.journey.add(this.form)
        if (res.code === 200) {
          uni.showToast({ title: '发布成功', icon: 'success' })
          uni.setStorageSync('journeyQuery', { type: this.form.type })
          setTimeout(() => uni.redirectTo({ url: '/pages/index/index' }), 1500)
        } else {
          uni.showToast({ title: res.msg || '发布失败', icon: 'none' })
        }
      } catch (err) {
        if (err && err.length) {
          uni.showToast({ title: err[0].message, icon: 'none' })
        } else {
          uni.showToast({ title: '表单校验失败', icon: 'none' })
        }
      }
    },
    handleBack() {
      uni.redirectTo({ url: '/pages/index/index' })
    }
  }
}
</script>

<style scoped>
.publish-page {
  background-color: #fff;
  margin: 30rpx;
}

.remark-info {
  text-align: right;
  margin-top: 5rpx;
  font-size: 24rpx;
}

.textarea-wrapper {
  position: relative;
  width: 100%;
}

.remark-counter {
  position: absolute;
  right: 10rpx;   /* 距离右边 10rpx */
  bottom: 10rpx;  /* 距离底部 10rpx */
  font-size: 24rpx;
  pointer-events: none; /* 避免挡住输入 */
}

</style>